package data;

import java.util.List;

import com.EntityName;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;

public class Hotel extends AbstractData {
	private long hotelId;
	private String hotelCode;
	private String hotelName;
	
	private final int codelength = 20;

	public Hotel()
	{
	}
	
	public Hotel(long id)
	{
		this.hotelId = id;
	}
	
	@Override
	public long getId() {
		return getHotelId();
	}
	public void setId(long id) {
		setHotelId(id);
	}
	public long getHotelId() {
		return hotelId;
	}
	public void setHotelId(long hotelId) {
		this.hotelId = hotelId;
		String code = String.format("%d%x",hotelId,(int)(Math.random()*6) + 10);
			
		for(int i=code.length();i<codelength;i++)
			code += String.format("%x",(int)(Math.random()*0x10));
		
		// TODO : workaround fix code must be removed
			code = hotelId + "e82ccaa4acf124ad345";
			
		this.hotelCode = code;
	}
	public String getHotelCode() {
		return hotelCode;
	}
	public String getHotelName() {
		return hotelName;
	}
	public void setHotelName(String hotelName) {
		this.hotelName = hotelName;
	}
	

	@Override
	public Entity getEntity() {
		Entity item;
		if(this.key == null)
			item = new Entity(EntityName.Hotel);
		else
			item = new Entity(this.key);

		item.setProperty("hotelId", this.hotelId);
		item.setProperty("hotelCode", this.hotelCode);
		item.setProperty("hotelName", this.hotelName);
		return item;
	}
	@Override
	public void setEntity(Entity entity) {
		this.hotelId = (Long) entity.getProperty("hotelId");
		this.hotelCode = (String) entity.getProperty("hotelCode");
		this.hotelName = (String) entity.getProperty("hotelName");
		this.key = entity.getKey();
	}
	
	public void LoadData() {
		if (this.hotelId > -1) {
			Entity entity = SearchHotelId(this.hotelId);
			if(entity != null)
				setEntity(entity);
		}
	}
	
	private Entity SearchHotelId(long key)
	{
		Filter filter = new FilterPredicate("hotelId",
				                      FilterOperator.EQUAL,
				                      key);
		Query q = new Query(EntityName.Hotel).setFilter(filter);
		PreparedQuery pq = datastore.prepare(q);
		List<Entity> list = pq.asList(FetchOptions.Builder.withLimit(1));
		if(list == null || list.size() == 0)
			return null;
		else
			return list.get(0);
	}
}
